import React, {
  useEffect,
  useState,
  useMemo,
  useCallback,
  CSSProperties
} from 'react';
import { SketchPicker } from 'react-color';
import { Tooltip } from 'antd';
import { TooltipPlacement } from 'antd/lib/tooltip';

import styles from './index.module.less';

export interface ColorPickerProps {
  value?: string;
  style?: CSSProperties;
  children?: string | JSX.Element;
  placement?: TooltipPlacement;
  onChange?: (color: string) => void;
}

const defaultPresetColors = [
  '#000000',
  '#FFFFFF',
  '#D0021B',
  '#FF6600',
  '#F5A623',
  '#F8E71C',
  '#8B572A',
  '#7ED321',
  '#417505',
  '#BD10E0',
  '#9013FE',
  '#4A90E2',
  '#50E3C2',
  '#B8E986',
  '#4A4A4A',
  '#9B9B9B'
];

const ColorPicker = (props: ColorPickerProps): JSX.Element => {
  const { value, children, placement, onChange, style } = props;
  const [color, setColor] = useState<string>('');
  const [colorInput, setColorInput] = useState<string>('');

  const colorChangeHandle = useCallback((color) => {
    setColor(color.hex);
  }, []);

  const colorChangeCompleteHandle = useCallback(
    (color) => {
      setColor(color.hex);
      onChange && onChange(color.hex);
    },
    [onChange]
  );

  useEffect(() => {
    if (value) {
      setColor(value);
      setColorInput(value?.substr(1));
    }
  }, [value]);

  const colorInputClickHandle = useCallback((e: React.MouseEvent) => {
    e.stopPropagation();
  }, []);

  const colorInputHandle = useCallback(
    (e: React.FormEvent<HTMLInputElement>) => {
      e.stopPropagation();
      const target = e.target as HTMLInputElement;
      const text = target.value;

      if (/^[0-9a-fA-F]{0,6}$/.test(text)) {
        setColorInput(text);
      }
      if (/^[0-9a-fA-F]{6}$/.test(text)) {
        setColor('#' + text);
        onChange && onChange('#' + text);
      }
    },
    [onChange]
  );

  const defaultChildren = useMemo(() => {
    return (
      <div className={styles['color-form']} style={style}>
        <div
          style={{ backgroundColor: color }}
          className={styles['color-box']}
        ></div>
        <input
          onClick={colorInputClickHandle}
          onChange={colorInputHandle}
          value={colorInput}
        />
      </div>
    );
  }, [color, colorInput, colorInputClickHandle, colorInputHandle, style]);

  return (
    <div className={styles['color-picker']}>
      <Tooltip
        color="#fff"
        overlayClassName={styles['color-select']}
        trigger={['click']}
        placement={placement}
        arrowPointAtCenter
        title={
          <SketchPicker
            disableAlpha
            color={color}
            presetColors={defaultPresetColors}
            onChange={colorChangeHandle}
            onChangeComplete={colorChangeCompleteHandle}
          />
        }
      >
        <div>{children ? children : defaultChildren}</div>
      </Tooltip>
    </div>
  );
};

export default ColorPicker;
